class Solution {
    public int minCostConnectPoints(int[][] points) {
        List<int[]> edges = new ArrayList<>();
        for (int i = 0; i < points.length; i++) {
            for (int j = i + 1; j < points.length; j++) {
                edges.add(new int[]{i, j, Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1])});
            }
        }
        edges.sort((a1, a2) -> a1[2] - a2[2]);
        disjointSet = new int[points.length];
        for (int i = 0; i < disjointSet.length; i++) {
            disjointSet[i] = i;
        }
        int ans = 0;
        for (int[] edge : edges) {
            int root1 = find(edge[0]);
            int root2 = find(edge[1]);
            if (root1 != root2) {
                disjointSet[root1] = root2;
                ans += edge[2];
            }
        }
        return ans;
    }
    private int find(int x) {
        if (disjointSet[x] == x) return x;
        return disjointSet[x] = find(disjointSet[x]);
    }
    private int[] disjointSet;
}
